package com.satan.upload.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.satan.upload.entity.Chunk;
import com.satan.upload.mapper.ChunkMapper;
import com.satan.upload.service.ChunkService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
* @author Demon
* @description 针对表【tb_chunk】的数据库操作Service实现
* @createDate 2023-09-13 14:28:42
*/
@Service
public class ChunkServiceImpl extends ServiceImpl<ChunkMapper, Chunk>
    implements ChunkService{

    @Override
    public Boolean saveChunk(MultipartFile chunk, String md5, Integer index, Long chunkSize, String resultFileName) {
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(resultFileName, "rw")) {
            // 偏移量
            long offset = chunkSize * (index - 1);
            // 定位到该分片的偏移量
            randomAccessFile.seek(offset);
            // 写入
            randomAccessFile.write(chunk.getBytes());
            Chunk saveChunk = Chunk.builder().cMd5(md5).cIndex(index).build();
            return save(saveChunk);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Integer> selectChunkListByMd5(String md5) {
        //select * from chunk where c_md5 = #{md5}
        LambdaQueryWrapper<Chunk> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Chunk::getCMd5, md5 );

        List<Chunk> chunkList = list(lambdaQueryWrapper);
        List<Integer> indexList = new ArrayList<>();
        for (Chunk chunk : chunkList) {
            indexList.add(chunk.getCIndex());
        }
        return indexList;
    }

    @Override
    public Boolean deleteChunkByMd5(String md5) {
        // delete from chunk where c_md5 = #{md5}
        LambdaQueryWrapper<Chunk> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Chunk::getCMd5,md5);
        boolean removed = remove(lambdaQueryWrapper);
        return removed;
    }

    @Override
    public byte[] getChunk(Integer index, Integer chunkSize, String resultFileName, long offset) {
        File resultFile = new File(resultFileName);
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(resultFileName, "r")) {
            // 定位到该分片的偏移量
            randomAccessFile.seek(offset);
            //读取
            byte[] buffer = new byte[chunkSize];
            randomAccessFile.read(buffer);
            return buffer;
        } catch (IOException e) {
            e.printStackTrace();

        }
        return null;
    }
}




